import Loading from '@/views/common/loading.vue'

function createLoading(el) {
  // 创建div标签
  const loadingDom = document.createElement('div')
  // 添加自定义属性作为标识，避免重复loading
  loadingDom.setAttribute('data-v', 'loading')
  // 设置样式，父元素相对定位，子元素绝对定位父元素之上
  // el.style.position = 'relative'
  // loadingDom.style.width = `${el.offsetWidth}px`
  // loadingDom.style.height = `${el.offsetHeight}px`
  // loadingDom.style.maxHeight = '100vh'
  // loadingDom.style.position = `absolute`
  // loadingDom.style.background = `black`
  // loadingDom.style.display = `flex`
  // loadingDom.style.justifyContent = `center`
  // loadingDom.style.alignItems = `center`
  // loadingDom.style.opacity = '.16'
  // loadingDom.style.top = '0'
  // loadingDom.style.borderRadius = 'inherit'
  // 创建APP实例，传入loading组件，并且挂载loading组件和创建的标签
  const app = createApp(Loading)
  const instance = app.mount(loadingDom)
  loadingDom.appendChild(instance.$el)
  el.appendChild(loadingDom)
}

// 创建自定义指令
const eLoading = {
  //mounted的时候，v-loading变量值为true时，加载loading
  mounted(el, binding) {
    if (binding.value === true) {
      createLoading(el)
    }
  },
  //update的时候
  updated(el, binding) {
    //v-loading 的值为false，并且该节点下最后一个元素是loading时，移除节点
    if (binding.value === false && el.lastChild.dataset.v === 'loading') {
      el.removeChild(el.lastChild)
      return
    }
    //v-loading 的值为true，并且该节点下没有loading节点时，调用函数，挂载loading
    if (binding.value === true && el.lastChild.dataset.v !== 'loading') {
      createLoading(el)
    }
  },
}

//导出创建好的指令
export default eLoading
